var IBizDataGrid4Editor = {
	createAutoEditor: function(ui, editorField , ctrl, valueField){
		var rowData = ui.rowData;
		var editorType = rowData[editorField];
		if(editorType == "TEXT"){
			this.createTextBox(ui, valueField);
		}else if(editorType == "DATE"){
			this.createDatePicker(ui, valueField, "YYYY-MM-DD", ctrl);
		}else if(editorType == "DATETIME"){
			this.createDatePicker(ui, valueField, "YYYY-MM-DD hh:mm:ss", ctrl);
		}else if(editorType == "CODELIST"){
			this.createPicker(ui, ctrl, valueField);
		}else{
			this.createTextBox(ui, valueField);
		}
	},
	//该字段为文本值/数字
	createTextBox: function(ui, valueField){
		var $cell = ui.$cell,
		rowData = ui.rowData,
		dataIndx = ui.dataIndx,
		cls = ui.cls,
		dc = $.trim(rowData[dataIndx]);
		$cell.css('padding', '0');
		$cell.addClass("ibiz-editor-cell");
		
		var $inp = $("<input type='text' style='padding:0;' name='" + dataIndx + "' class='" + cls + " pq-cell-editor'/>" )
		.appendTo($cell)
		.width($cell.width()-4)
		.height($cell.height()-2)
		.css("outline","none")
		.val(dc);
	}
	//该字段为时间日期
	,createDatePicker: function(ui, valueField, format, ctrl){
		var $cell = ui.$cell,
		rowData = ui.rowData,
		dataIndx = ui.dataIndx,
		cls = ui.cls,
		dc = $.trim(rowData[dataIndx]);
		$cell.css('padding', '0');
		$cell.addClass("ibiz-editor-cell");
		
//		$cell.addClass("ibiz-field-datepicker");
		var id = dataIndx+Math.ceil(Math.random()*1000);
		var $inp = $("<input id='"+id+"' style='width: 100%;padding: 4px 3px;' type='text' name='" + dataIndx + "' class='" + cls + " pq-cell-editor' readonly/>" )
	    .appendTo($cell)
	    .val(dc);
		if(valueField.format){
			format = valueField.format;
		}
		if(format) {
			format = format.replace(/HH/g, "hh");
		}
//		var date = new IBizDateField({id:id,name:'start',fmt:format,allowBlank:false,width:$cell.width()-6,height:$cell.height()});
		jeDate("#"+id,{
            format: format,
            theme:{ bgcolor:"#5b9bd1",color:"#ffffff", pnColor:"#bbbbbb"},
            donefun: function(obj) {
            	ctrl.getMDCtrl().grid.pqGrid("quitEditMode");
            }
        });
        setTimeout(function(){
        	$("#"+id).click();
        },100);
        ctrl.getMDCtrl().grid.on( "pqgrideditorblur", function( event, ui ) {
			return false;
		} );
	}
	//该字段为代码表
	,createDropDownList: function(ui,ctrl,config){
		var me = this;
		var $cell = ui.$cell,
		rowData = ui.rowData,
		dataIndx = ui.dataIndx,
		cls = ui.cls,
		dc = $.trim(rowData[dataIndx]);
		$cell.css('padding', '0');
		$cell.addClass("ibiz-editor-cell");
		
		var $inp = $('<select class="' + cls + ' pq-cell-editor"></select>')
		.appendTo($cell)
		.width($cell.width()-6)
		.height($cell.height()-4);
		
		if(config.codeListType == 'STATIC'){
			var datas = ctrl.getCodeList(config.codeListId).datas;
			$cell.find(".pq-cell-editor").append('<option value=""></option>');
			for(var i=0;i<datas.length;i++){
				var option = "";
				if(dc == datas[i].value){
					option = '<option value="'+datas[i][config.valueField]+'" selected="selected">'+datas[i][config.displayField]+'</option>';
				}else{
					option = '<option value="'+datas[i][config.valueField]+'">'+datas[i][config.displayField]+'</option>';
				}
				$cell.find(".pq-cell-editor").append(option);
			}
			$cell.find(".pq-cell-editor").on("change",function(event){
				ctrl.getMDCtrl().grid.pqGrid("quitEditMode");
			});
		}else if(config.codeListType == 'DYNAMIC'){
			var param = {};
			if(config.param){
				param = config.param;
			}
			param.srfreferdata = JSON.stringify(ui.rowData);
			$.extend(param,rowData);
			IBiz.ajax({
				url: ctrl.getAppCtx()+config.url,
				params: param,
				method: 'POST',
				dataType: 'json',
				success: function(result) {
					if(result.success){
						var datas = result[config.reader.rootProperty];
						$cell.find(".pq-cell-editor").append('<option name="" value=""></option>');
						for(var i=0;i<datas.length;i++){
							if(ui.rowData[config.valueItem] == datas[i][config.valueField]){
								$cell.find(".pq-cell-editor").append('<option name="'+datas[i][config.valueField]+'" value="'+datas[i][config.displayField]+'" selected="selected">'+datas[i][config.displayField]+'</option>');
							}else{
								$cell.find(".pq-cell-editor").append('<option name="'+datas[i][config.valueField]+'" value="'+datas[i][config.displayField]+'">'+datas[i][config.displayField]+'</option>');
							}
						}
					}
				},
				failure: function(e) {
					IBiz.alert($IGM('IBIZAPP.CONFIRM.TITLE.INFO','信息'));
				}
			});
			$cell.find(".pq-cell-editor").on("change",function(event){
				var value = $cell.find(".pq-cell-editor option:selected").attr("name");
				var text = $cell.find(".pq-cell-editor option:selected").html();
				var param = {rowIndx:ui.rowIndx,rowData:ui.rowData,dataIndx:config.valueItem,newVal:value,oldVal:ui.rowData[config.valueItem]};
				ui.rowData[config.valueItem] = value;
				me.fireData(ctrl,param);
				ctrl.getMDCtrl().grid.pqGrid("quitEditMode");
			});
		}
	}
	//该字段为通过页面回填数据
	,createPicker: function(ui,ctrl,config){
		var me = this;
		var $cell = ui.$cell,
		rowData = ui.rowData,
		dataIndx = ui.dataIndx,
		cls = ui.cls,
		dc = $.trim(rowData[dataIndx]);
		$cell.css('padding', '0');
		$cell.addClass("ibiz-editor-cell");
		
		var linkWidth = 0;
		var linkSpan = "";
		if(config.linkurl){
			linkWidth = 21;
			linkSpan = '<span class="linkview fa fa-external-link-square" aria-hidden="true"></span>';
		}
		
		var dropWidth = 0;
		var dropSpan = "";
		if(config.trigger){
			dropWidth = 14;
			dropSpan = '<span style="right:'+(linkWidth+8)+'px;" class="dropDown fa fa-angle-down" aria-hidden="true"></span>';
		}
		
		var pickupWidth = 0;
		var pickupSpan = "";
		if(config.pickupView){
			pickupWidth = 18;
			pickupSpan = '<span class="fa fa-search" style="right:'+(linkWidth+8)+'px;"></span>';
		}
		
		var editDiv = '<div>'+pickupSpan+dropSpan+linkSpan;
		editDiv += '<input class="' + cls + ' pq-cell-editor text" name="' + dataIndx+'" style="width:'+($cell.width()+1)+'px;height:'+($cell.height()+1)+'px;padding-right:'+(linkWidth+pickupWidth+dropWidth)+'px;">';
		editDiv += '<div id="selectDown" style="display:none;width:'+($cell.width()+1)+'px;"></div></div>';
		
		var $inp = $(editDiv)
		.appendTo($cell)
		.css('padding', '0');
		$cell.find(".pq-cell-editor").val(dc);
		
		if(config.ac != undefined && !config.ac){
			$cell.find(".pq-cell-editor").attr("readOnly",true);
		}else{
			me.openPickupAC(ui,ctrl,config,$inp);
		}
		
		$(".ibiz-editor-cell .dropDown").click(function(){
			$cell.find("#selectDown").empty();
			me.openPickupDown(ui,ctrl,config);
		});
		
		$(".ibiz-editor-cell #selectDown").on("click",".dropOption",function(event){
			var text = $(this).text();
			var value = $(this).attr("name");
			$cell.find(".pq-cell-editor").val(text);
			ui.rowData[config.valueItem] = value;
			var colModel = ctrl.getMDCtrl().grid.pqGrid("option","colModel");
			for (var i = 0, len = colModel.length; i < len; i++) {
				if (colModel[i].dataIndx == config.valueItem) {
					ctrl.getMDCtrl().grid.pqGrid( "refreshCell", { rowIndx: ui.rowIndx, dataIndx: config.valueItem } );
				}
			}
			$cell.find("#selectDown").hide();
			ctrl.getMDCtrl().grid.pqGrid("quitEditMode");
		});
		
		$(".ibiz-editor-cell .linkview").click(function(){
			$("#selectDown").hide();
			if(ui.rowData[config.valueItem]){
				me.openEditorView(config.linkurl,ui.rowData[config.valueItem]);
			}
		});
		
		$(".ibiz-editor-cell .fa-search").click(function(event){
			me.flag = true;
			$("#selectDown").hide();
			me.openPickerView(ui,ctrl,config);
		});
	}
	,openPickupDown: function(ui,ctrl,config){
		if(!config.dataurl){
			IBiz.alert($IGM('IBIZAPP.CONFIRM.TITLE.INFO','数据地址不存在！'));
		}
		var param = {srfreferdata: JSON.stringify(ui.rowData)};
		IBiz.ajax({
			url: ctrl.getAppCtx()+config.dataurl,
			params: param,
			method: 'POST',
			dataType: 'json',
			success: function(result) {
				if(result.success){
					var datas = result.items;
					for(var i=0;i<datas.length;i++){
						$("#selectDown").append('<div class="dropOption" name="'+datas[i][config.valueField]+'">'+datas[i][config.displayField]+'</div>');
					}
					$("#selectDown").show();
				}
			},
			failure: function(e) {
				IBiz.alert($IGM('IBIZAPP.CONFIRM.TITLE.INFO','信息'));											
			}
		});
	}
	//开启数据选择AC功能
	,openPickupAC: function(ui,ctrl,config,$inp){
		var me = this;
		$inp.autocomplete({  //绑定AC事件
			type:'POST',
			minChars: config.minChars,
			serviceUrl : function() {
				return ctrl.getAppCtx()+config.acdataurl;
			},
			onSelect : function(data) {
				var id = data.data;
				if(id && id != ''){
					ui.rowData[config.valueItem] = id;
					var colModel = ctrl.getMDCtrl().grid.pqGrid("option","colModel");
					for (var i = 0, len = colModel.length; i < len; i++) {
						if (colModel[i].dataIndx == config.valueItem) {
							ctrl.getMDCtrl().grid.pqGrid( "refreshCell", { rowIndx: ui.rowIndx, dataIndx: config.valueItem } );
						}
					}
					ctrl.getMDCtrl().grid.pqGrid("quitEditMode");
				}
				me.flag2 = true;
			},
			onSearchStart : function(params) {
				$("#selectDown").hide();
				var curparams = {
						srfaction : 'itemfetch'
				};
				if(me.flag){
					me.flag = false;
					return false;
				}
				
				ui.rowData[config.valueItem] = '';
				params = $.extend(params, curparams);
				params.srfreferitem = ui.dataIndx;
				params.srfreferdata = JSON.stringify(ui.rowData);
				params['limit'] = config.pageSize;
				return true;
			},
			transformResult : function(response) {
				var data = (typeof response === 'string' ? $.parseJSON(response) : response);
				var items = [];
				if (data.ret == 0) {
					$.each(data.items, function(index, item) {
						var text = item.text ? item.text.toString(): $IGM('IBIZPICKERFIELD.TRANSFORMRESULT.INFO','未定义');
						var data = item.value ? item.value.toString(): '';
						items.push({
							value : text,
							data : data
						});
					});
				}
				if(items.length == 0){
					items.push({
						value : $IGM('IBIZPICKERFIELD.TRANSFORMRESULT.INFO2','找不到符合的数据'),
						data : ''
					});
				}
				return {
					'suggestions' : items
				};
			}
		});
	}
	//打开实体编辑页面
	,openEditorView: function(url,srfkey){
		var win = $.ibizapp.createWindow({});
		var viewparam = {};
		viewparam['windowid'] = win.getId();
		win.title = '';
		win.url = $.getIBizApp().parseURL(BASEURL, url, {
			windowid : win.getId()
		});
		win.url += "&srfkey="+srfkey;
		win.viewparam = viewparam;
		win.openModal(window);
	}
	//打开选择页面
	,openPickerView: function(ui,ctrl,config){
		var me = this; 
		var win = $.ibizapp.createWindow({});
		var viewparam={};
		viewparam['windowid'] = win.getId();
		viewparam.srfreferdata = JSON.stringify(ui.rowData);
		win.title = config.pickupView.title;
		win.url = $.getIBizApp().parseURL(BASEURL, config.pickupView.view, {
			windowid : win.getId()
		});
		win.viewparam = viewparam;
		win.callback = function(win){
			me.pickerViewClose(ui,ctrl,win,config);
		};
		win.openModal(window);
	}
	//关闭弹窗后回填数据
	,pickerViewClose: function(ui,ctrl,win,config){
		var rowData = ui.rowData;
		if(win.dialogResult == 'ok'){
			var select = win.selectedData;
			rowData[config.valueItem] = select.srfkey;
			$(".pq-cell-editor").val(select.srfmajortext);
			ctrl.getMDCtrl().grid.pqGrid( "refreshCell", { rowIndx: ui.rowIndx, dataIndx: config.valueItem } );
			ctrl.getMDCtrl().grid.pqGrid("quitEditMode");
		}
	}
	,fireData: function(ctrl,args){
		ctrl.getMDCtrl().fireEvent(IBizDataGrid.UPDATEGRIDITEMCHANGE,ctrl,args);
	}
};
